<template>
  <div class="app-container">
    <div class="search-container">
      <el-input v-model="searchForm.username" prefix-icon="el-icon-search" clearable placeholder="请输入用户名" class="search-input" @keyup.enter.native="getList({pageNo:1})" />
      <el-button type="primary" icon="el-icon-search" size="small" @click="getList({pageNo: 1})">搜索</el-button>
    </div>
    <div class="function-buttons" />
    <div>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
        <el-table-column align="center" label="#" width="80" type="index" />
        <el-table-column align="center" label="所属部门">
          <template slot-scope="scope">
            <span>{{ scope.row.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="职位">
          <template slot-scope="scope">
            <span>{{ scope.row.jobName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户名">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="昵称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="邮箱">
          <template slot-scope="scope">
            <span>{{ scope.row.email }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="手机号">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="添加时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人">
          <template slot-scope="scope">
            <span>{{ scope.row.operator }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="update(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="pageChange" />
    </div>
    <div>
      <el-dialog title="详情" :visible.sync="saveForm.visible" :close-on-click-modal="false">
        <el-form ref="saveForm" :model="saveForm.props" :rules="saveForm.rules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="saveForm.props.username" disabled="true" />
          </el-form-item>
          <el-form-item label="昵 称" prop="name">
            <el-input v-model="saveForm.props.name" disabled="true" />
          </el-form-item>
          <el-form-item label="职位">
            <el-input v-model="saveForm.props.jobName" disabled="true" />
          </el-form-item>
          <el-form-item label="所属部门" prop="deptIdList">
            <el-cascader
              ref="cascader"
              v-model="saveForm.props.deptTreeList"
              :options="deptTreeList"
              :props="{ multiple: true, checkStrictly: true }"
              clearable
              disabled="true"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="电 话" prop="phone">
            <el-input v-model="saveForm.props.phone" disabled="true" />
          </el-form-item>
          <el-form-item label="邮 箱" prop="email">
            <el-input v-model="saveForm.props.email" disabled="true" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('saveForm')">关闭</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="角色" :visible.sync="roleForm.role">
        <el-checkbox-group v-model="checkList">
          <el-table :data="roles" border fit highlight-current-row>
            <el-table-column align="center" label="描 述">
              <template slot-scope="scope">
                <span>{{ scope.row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="角色名">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label=" " width="100px" type="index">
              <template slot-scope="scope">
                <el-checkbox :label="scope.row.id" class="role-checkbox" />
              </template>
            </el-table-column>
          </el-table>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button @click="roleForm.role = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import request from '@/utils/request'

export default {
  name: 'TopicList',
  components: { Pagination },
  data() {
    const passwordRule = (rule, value, callback) => {
      if (!rule.required && !this.saveForm.props.password) {
        callback();
      }
      const regExp = /^(?![0-9]+$)(?![a-zA-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\$\^]+$)[0-9A-Za-z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\$\^]{8,16}$/;
      if (!regExp.test(this.saveForm.props.password)) {
        callback(new Error('密码由数字、字母、特殊字符组成，且长度要在8-16位之间。'));
      } else {
        callback();
      }
    };
    return {
      checkList: [],
      delUser: false,
      uploadAction: this.cfg.apiDomain + '/file/upload/upload?uploadItem=topicPostImg',
      list: null,
      keywords: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      roles: null,
      currentRole: null,
      roleForm: {
        role: false,
        userId: '',
        props: {
          id: '',
          name: '',
          description: ''
        }
      },
      searchForm: {
        username: '',
        tag: ''
      },
      deptTreeList: [],
      saveForm: {
        visible: false,
        props: {
          id: '',
          username: '',
          password: '',
          name: '',
          phone: '',
          email: '',
          operator: '',
          createTime: '',
          tag: '',
          deptTreeList: [],
          isSecondLanding: ''
        },
        rules: {
          username: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          password: [{ required: true, trigger: 'blur', validator: passwordRule }],
          passwords: [{ required: false, trigger: 'blur', validator: passwordRule }],
          phone: this.formRules({
            required: true,
            min: 1,
            max: 20,
            type: 'phoneNumber'
          }),
          name: this.formRules({
            required: true,
            min: 1,
            max: 50
          }),
          email: this.formRules({
            required: true,
            min: 1,
            max: 100,
            type: 'email'
          }),
          postImgPath: this.formRules({
            required: true
          }),
          title: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          announcement: this.formRules({
            required: true,
            min: 1,
            max: 200
          }),
          validDateRange: this.formRules({
            type: 'array',
            required: true
          }),
          contentPath: this.formRules({
            required: true
          })
        }
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.getDeptTreeList();
    this.getList({
      pageNo: this.listQuery.pageNo
    })
  },
  methods: {
    updateElCascaderStyle(value) {
      // 效果：项目名称的input框随着内容的长度而自适应，设置 el_cascader 标签的width
      var el_cascader_element = document.querySelector('#el-cascader')
      var length = value.join('.').length + 1
      var num =  length * 9  + 'px'
      el_cascader_element.style.width = num
    },
    getDeptTreeList() {
      var _this = this;
      request({
        method: 'post',
        url: `/system/sysDept/getDeptTreeList`
      }).then(res => {
        _this.deptTreeList = res.data
      })
    },
    pageChange(page) {
      this.getList({
        pageNo: page.page
      })
    },
    getList() {
      this.listLoading = true
      request({
        url: '/system/sysUser/getDataPermissionPageList',
        method: 'post',
        data: {
          status: 0,
          pageNo: this.listQuery.pageNo,
          pageSize: this.listQuery.pageSize,
          ...this.searchForm
        }
      }).then(res => {
        const data = res.data
        this.list = data.rows
        this.total = data.total
        this.listLoading = false
      })
    },
    getRoleList() {
      const _this = this;
      request({
        url: '/system/sysRole/getPageList',
        method: 'post',
        data: {
          pageNo: 1,
          pageSize: 100
        }
      }).then(res => {
        const data = res.data
        _this.roles = data.rows
      })
    },
    save() {
      this.saveForm.props = {
        id: '',
        username: '',
        name: '',
        password: '',
        phone: '',
        email: '',
        operator: '',
        createTime: '',
        tag: '',
        deptTreeList: [],
        tagList: [],
        isSecondLanding: '0'
      };
      this.saveForm.visible = true
    },
    update(data) {
      this.saveForm.props = {
        id: data.id,
        username: data.username,
        password: '',
        phone: data.phone,
        email: data.email,
        name: data.name,
        jobName: data.jobName,
        tag: data.tag,
        deptTreeList: data.deptTreeList,
        tagList: data.tagList == null ? [] : data.tagList,
        isSecondLanding: data.isSecondLanding.toString()
      };
      this.saveForm.visible = true
    },
    del(id) {
      request({
        url: '/system/sysUser/delete',
        method: 'post',
        params: {
          id: id
        }
      }).then(res => {
        this.$message.success('删除成功')
        this.getList({
          pageNo: 1
        });
        this.delUser = false;
      })
    },
    doSave() {
      const _this = this;
      this.$refs.saveForm.validate(valid => {
        if (!valid) {
          return;
        }
        _this.saveForm.props.deptIdList = [];
        for (var i = 0; i < _this.saveForm.props.deptTreeList.length; i++) {
          var valElement = _this.saveForm.props.deptTreeList[i];
          _this.saveForm.props.deptIdList.push(valElement[valElement.length - 1]);
        }
        _this.saveForm.props.tag = _this.saveForm.props.tagList.toString();
        request({
          url: '/system/sysUser/save',
          method: 'post',
          data: {
            id: _this.saveForm.props.id,
            username: _this.saveForm.props.username,
            password: _this.saveForm.props.password,
            phone: _this.saveForm.props.phone,
            name: _this.saveForm.props.name,
            email: _this.saveForm.props.email,
            tag: _this.saveForm.props.tag,
            deptIdList: _this.saveForm.props.deptIdList,
            isSecondLanding: _this.saveForm.props.isSecondLanding
          }
        }).then(res => {
          _this.$message.success('保存成功');
          _this.getList({
            pageNo: 1
          });
          _this.saveForm.visible = false;
        })
      });
    },
    getCurrentRole(id) {
      const _this = this;
      request({
        url: 'system/sysUserRole/getPageList',
        method: 'post',
        data: {
          sysUserId: id,
          pageNo: 1,
          pageSize: 100
        }
      }).then(res => {
        const data = res.data.rows
        var roleIds = [];
        for (var i = 0; i < data.length; i++) {
          roleIds.push(data[i]['sysRoleId'])
        }
        _this.checkList = roleIds
      })
    },
    role(id) {
      this.checkList = [];
      this.getRoleList()
      this.getCurrentRole(id)
      this.roleForm.props = {
        id: '',
        name: '',
        description: ''
      };
      this.roleForm.role = true
      this.roleForm.userId = id
    },
    addRole() {
      request({
        url: '/system/sysUserRole/addRole',
        method: 'post',
        data: {
          newRole: this.checkList,
          userId: this.roleForm.userId
        }
      }).then(res => {
        this.$message.success('分配成功')
        this.roleForm.role = false;
      })
    },
    postImgUploadSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error('上传失败: ' + res.message);
        return;
      }
      this.saveForm.props.postImgPath = res.data.url;
    },
    // 取消
    cancel(formName) {
      this.$refs[formName].clearValidate();
      this.$refs[formName].resetFields();
      this.saveForm.visible = false;
    }
  }
}
</script>

<style>
  .role-checkbox .el-checkbox__label {
    display: none;
  }
</style>
